'use strict';
const path = require('path');

const Processor = require('./base_processor');
const { ExcelColumns } = require('./base_processor');
const StringUtil = require('./util/string_util');
const Logger = require('../lib/log/logger');
const LogUtil = require('../lib/util/log_util');
const RCMSCategoriesStore = require('./store/rcms_categories_store');

// 虚拟栏目
const VIRTUAL_CATEGORY = ['首页'];
// excel栏目名和数据库栏目名的映射,value:excel;realValue:数据库
const REAL_CATE_MAPPING = [
  {
    value: '政府信息公开',
    realValue: '信息公开'
  },
  {
    value: '易军',
    realValue: '易　军'
  },
  {
    value: '倪虹',
    realValue: '倪　虹'
  },
  {
    value: '黄艳',
    realValue: '黄　艳'
  },
  {
    value: '常青',
    realValue: '常　青'
  },
  {
    value: '赵晖',
    realValue: '赵　晖'
  }
];
// 确定的老栏目id
const EXACTLY_OLD_COLUMN_ID = [
  {
    fullname: '政策发布',
    id: 2666
  }
];
// 忽略的老栏目
const IGNORE_OLD_COLUMN = ['政府信息公开 >> 信息公开目录', '政府信息公开 >> 目录下载'];

class OldProcessor extends Processor {
  constructor(filePath) {
    super(filePath, 'OldProcessor');
    this.logger = new Logger(
      'OldProcessor',
      LogUtil.getFileLogWriter('OldProcessor', path.basename(this.outputFilePath))
    );
  }
  /**
   * 业务逻辑
   * read >> process >> write
   * @return {String} 输出文件路径
   */
  async process() {
    // 处理之前先清空日志，避免日志过多不方便查看
    this.logger.clear();

    const oldDbRows = await RCMSCategoriesStore.list();

    const excelRows = this.read();

    let currentRowIndex = 1;
    let newExcelRows = [];
    for (const excelRow of excelRows) {
      currentRowIndex++;
      const oldColumn = excelRow[ExcelColumns.OLD_COLUMN];
      const oldColumnList = StringUtil.splitOldColumn(oldColumn, REAL_CATE_MAPPING);

      this.fulfillOldColumnId(oldColumnList, oldDbRows);

      if (oldColumnList && oldColumnList.length > 0) {
        // 因为原来的一行变为了多行，这行本身也就不在了，所以需要--
        currentRowIndex--;
        const appendRows = oldColumnList.map(c => {
          currentRowIndex++;
          const newExcelRow = { ...excelRow };
          newExcelRow[ExcelColumns.OLD_COLUMN_NEW] = c.fullname;
          if (c.id) {
            newExcelRow[ExcelColumns.OLD_COLUMN_SITEID] = c.siteId;
            newExcelRow[ExcelColumns.OLD_COLUMN_ID] = c.id;
            newExcelRow[ExcelColumns.FILTER] = c.filter;
          } else {
            this.logger.info(
              `(${currentRowIndex})老栏目id未找到:${c.fullname}${
                IGNORE_OLD_COLUMN.indexOf(c.fullname) >= 0 ? '(忽略)' : ''
              }`
            );
          }
          return newExcelRow;
        });
        newExcelRows = newExcelRows.concat(appendRows);
      } else {
        newExcelRows.push(excelRow);
      }
    }
    this.write(newExcelRows);

    return this.outputFilePath;
  }

  /**
   * 填充老栏目的id
   * @param {Object[]} oldColumnList 老栏目列表
   * @param {String} oldColumnList[].name 老栏目名称
   * @param {Object} oldColumnList[].parent 老栏目的父栏目
   * @param {Object[]} oldDbRows 老栏目表的数据
   * @param {Number} oldDbRows[].id 老栏目id
   * @param {String} oldDbRows[].name 老栏目名称
   * @param {Number} oldDbRows[].parentid 老栏目父级id
   * @param {String} oldDbRows[].filter 老栏目文章筛选条件
   */
  fulfillOldColumnId(oldColumnList, oldDbRows) {
    if (!oldColumnList || oldColumnList.length === 0) {
      return;
    }
    for (const oldColumn of oldColumnList) {
      const findExactlyColumn = EXACTLY_OLD_COLUMN_ID.find(m => m.fullname === oldColumn.fullname);
      if (findExactlyColumn) {
        const exactRow = oldDbRows.find(x => x.id === findExactlyColumn.id);
        if (exactRow) {
          oldColumn.id = exactRow.id;
          oldColumn.filter = exactRow.filter;
          oldColumn.siteId = exactRow.siteId;
        }
        continue;
      }
      const matchRows = oldDbRows.filter(m => m.name === oldColumn.name);
      const hasValidRow = matchRows.findIndex(m => m.status === 1) >= 0;
      if (matchRows && matchRows.length > 0) {
        for (const row of matchRows) {
          if (oldColumn.parent && !this.isVirtualCategory(oldColumn.parent.name)) {
            if (this.recursiveMatch(row, oldColumn.parent, oldDbRows, hasValidRow)) {
              oldColumn.id = row.id;
              oldColumn.filter = row.filter;
              oldColumn.siteId = row.siteId;
              break;
            }
          } else if (row.parentid === 0 && (row.status === 1 || !hasValidRow)) {
            oldColumn.id = row.id;
            oldColumn.filter = row.filter;
            oldColumn.siteId = row.siteId;
            break;
          }
        }
      }
    }
  }

  recursiveMatch(row, parent, oldDbRows, hasValidRow) {
    const findParent = oldDbRows.find(m => m.id === row.parentid && m.name === parent.name);
    // 如果excel中的列没有parent，数据库也没有parent，那就认定匹配
    if (!parent) {
      return !findParent;
    }
    // parent存在，但是该row的parent不存在，则未匹配
    if (!findParent) {
      return false;
    }
    if (findParent.name.trim() === parent.name) {
      // 如果上级是无效的，并且同级中还存在有效的栏目，则取有效的
      if (findParent.status === 0 && hasValidRow) {
        return false;
      }
      if (parent.parent && !this.isVirtualCategory(parent.parent.name)) {
        return this.recursiveMatch(findParent, parent.parent, oldDbRows, hasValidRow);
      }
      return true;
    }
    return false;
  }

  isVirtualCategory(name) {
    return VIRTUAL_CATEGORY.indexOf(name) >= 0;
  }
}

module.exports = OldProcessor;
